import { Router } from 'express'
import { rateLimit } from 'express-rate-limit'
import { auth } from '../middlewares/auth'
import { validate } from '../middlewares/validate'
import { AuthService } from '../services/auth/AuthService'

const router = Router()
const authService = new AuthService()

// 登录限制
const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 5, // 最多5次尝试
  message: '登录尝试次数过多，请15分钟后再试',
})

// 手机验证码登录
router.post('/login/phone', validate('phoneLogin'), async (req, res, next) => {
  try {
    const { phone, code } = req.body
    const result = await authService.loginByPhone(phone, code)
    res.json({
      code: 200,
      message: '登录成功',
      data: result,
    })
  } catch (error) {
    next(error)
  }
})

// 发送验证码
router.post('/sms/send', validate('phone'), async (req, res, next) => {
  try {
    const { phone } = req.body
    await authService.sendLoginCode(phone)
    res.json({
      code: 200,
      message: '验证码已发送',
      data: null,
    })
  } catch (error) {
    next(error)
  }
})

// 微信登录
router.post('/login/wechat', async (req, res, next) => {
  try {
    const { code } = req.body
    const result = await authService.loginByWechat(code)
    res.json({
      code: 200,
      message: '登录成功',
      data: result,
    })
  } catch (error) {
    next(error)
  }
})

// QQ登录
router.post('/login/qq', async (req, res, next) => {
  try {
    const { code } = req.body
    const result = await authService.loginByQQ(code)
    res.json({
      code: 200,
      message: '登录成功',
      data: result,
    })
  } catch (error) {
    next(error)
  }
})

// 刷新Token
router.post('/token/refresh', async (req, res, next) => {
  try {
    const { refreshToken } = req.body
    const result = await authService.refreshToken(refreshToken)
    res.json({
      code: 200,
      message: 'Token已更新',
      data: result,
    })
  } catch (error) {
    next(error)
  }
})

// 退出登录
router.post('/logout', auth, async (req, res, next) => {
  try {
    // 清除用户的登录状态
    res.json({
      code: 200,
      message: '已退出登录',
      data: null,
    })
  } catch (error) {
    next(error)
  }
})

export const authRoutes = router
